/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2011 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;

namespace AWZhome.NQ.CommonServices
{

	[NQExportedService(SingleInstance = true)]
	[NQServiceAttachment(NQCoreAttachLists.ServiceManager_PostServiceInit)]
	internal class SessionManagerService : Services.ISessionManagerService
	{
		private Dictionary<string, ISession> sessionList = new Dictionary<string, ISession>();
		private ISession defaultSession;

		public SessionManagerService()
		{
			// Register handler for service creation
			NQServiceManager.Instance.ServiceCreated += NQServiceManager_ServiceCreated;
		}

		~SessionManagerService()
		{
			// Some cleaning
			foreach (ISession session in sessionList.Values)
			{
				// Close the session
				if (!session.IsOpen)
				{
					session.CloseSession();
				}
			}
			defaultSession = null;
		}

		[NQServiceInvokeMethod]
		public void InitManager()
		{
			// Load static sessions
			ISession[] staticSessions =
				NQServiceManager.Instance.CreateAttachedServices<ISession>(
					BasicCommonAttachLists.SessionManager_StaticSessions
				);
			foreach (ISession session in staticSessions)
			{
				session.OpenSession();
			}
		}

		#region INQSessionManagerService Members

		public ISession DefaultSession
		{
			get
			{
				return defaultSession;
			}
		}

		public string GenerateSessionName(ISession session)
		{
			string sessionName = ServiceCore.ObjectMetaInfo(session).ServiceInterface.FullName + "|" + session.Context;
			int counter = 1;
			while (this[sessionName] != null)
			{
				sessionName = sessionName + "|" + counter;
				counter++;
			}

			return sessionName;
		}

		#endregion

		#region INQCollectionService<string, INQSessionService> Members

		public ISession this[string key]
		{
			get
			{
				if (sessionList.ContainsKey(key))
				{
					return sessionList[key];
				}
				else
				{
					return null;
				}
			}
		}

		public IEnumerator<ISession> GetEnumerator()
		{
			return ((IEnumerable<ISession>) sessionList.Values).GetEnumerator();
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return ((System.Collections.IEnumerable) sessionList.Values).GetEnumerator();
		}

		public int Count
		{
			get
			{
				return sessionList.Count;
			}
		}

		#endregion

		#region Private methods and event handlers

		private void NQServiceManager_ServiceCreated(object sender, NQServiceCreatedEventArgs e)
		{
			ISession tempSession = e.CreatedService as ISession;

			if (tempSession != null)
			{
				// Handle session initialization
				tempSession.SessionOpened += tempSession_SessionOpened;
			}
		}

		private void tempSession_SessionOpened(object sender, EventArgs e)
		{
			ISession tempSession = sender as ISession;
			if (tempSession != null)
			{
				tempSession.SessionOpened -= tempSession_SessionOpened;

				// A session has been opened, save the instance in internal list
				sessionList.Add(tempSession.SessionName, tempSession);

				// We want to be notified, when session is closed
				tempSession.SessionClosed += tempSession_SessionClosed;

				// Save if it is the default session
				if (tempSession.Protocol == "NQ_Default")
				{
					defaultSession = tempSession;
				}
			}
		}

		private void tempSession_SessionClosed(object sender, EventArgs e)
		{
			// Session has been closed, so remove it from internal list
			ISession tempSession = (ISession) sender;
			if (sessionList.ContainsKey(tempSession.SessionName))
			{
				tempSession.SessionClosed -= tempSession_SessionClosed;
				sessionList.Remove(tempSession.SessionName);
			}
		}

		#endregion
	}
}
